/*
 * OrderLineDAO.java
 *
 * Created on March 5, 2007, 8:08 PM
 *
 */

package edu.byu.isys413.group1E.data;

import edu.byu.isys413.group1E.*;
import java.sql.*;
import java.util.ArrayList;

/** Reads and writes OrderLineBO data to and from the database.
 *
 * @author Travis Kulbeth
 */
public class OrderLineDAO {
    
    /** Contains an instance of OrderLineDAO */
    private static OrderLineDAO instance = null;
    
    /** Creates a new instance of OrderLineDAO */
    private OrderLineDAO() {
    }
        
    /**Retrieves an instance of the OrderLineDAO object
     * @return an instance of OrderLineDAO
     */
    public static synchronized OrderLineDAO getInstance() {
        if (instance == null) {
            instance = new OrderLineDAO();
        }
        return instance;
    }
    
    ///////////////////////////////////////////////////////////////////////////////
    /////////   CREATE
    /** creates a new OrderLineBO object.
     *
     *@throws Exception for any errors encountered
     *@return new OrderLineBO
     */
    public OrderLineBO create() throws Exception{
        String id = GUID.generate();
        OrderLineBO bo = new OrderLineBO(id);
        Cache c = Cache.getInstance();
        c.put(bo.getOrderLineID(), bo);
        return bo;
    }
    
    //////////////////////////////////////////////////////////////////////////////
    //////////   READ
    /** This is the public read statement.  It loads an existing record
     * from the database by referencing the given id.
     *
     * @param id contains the unique identifier for the record to be read from the DB.
     * @throws edu.byu.isys413.group1E.DataException to catch any errors with the incoming data
     * @throws edu.byu.isys413.group1E.ConnectionPoolException to catch errors when connecting to the DB
     *
     * @return a TransactionBO containing the information extracted from the requested
     * tuple in the DB.
     */
    public synchronized OrderLineBO read(String id) throws DataException, ConnectionPoolException {
        // check to see if id in the cache
        Cache c = Cache.getInstance();
        OrderLineBO OrderLine = (OrderLineBO)c.get(id);
        if (OrderLine != null){
            return OrderLine;                                                        // if so, return it immediately
        }
        
        //otherwise, get it from the database
        try {
            Connection conn = ConnectionPool.getInstance().get();             // retrieve a database connection from the pool
            OrderLine = this.read(id, conn);                                              // call read with a connection
            conn.commit();
            ConnectionPool.getInstance().release(conn);                       // release the connection
        }catch (SQLException e) {
            //rollback
            throw new DataException("Could not retrieve record for Transaction Line ID = " + id, e);
        }catch (ConnectionPoolException x) {
            //rollback
            throw new ConnectionPoolException("Could not establish connection to database.", x);
        }
        
        // release the connection back to the pool
        return OrderLine;
    }
    
    /**
     * This is the public read statement.  It loads an existing OrderLine record
     * from the database based on the OrderLine id, using an already existing connection to the DB,
     * and returns a OrderLineBO.
     * 
     * 
     * @return OrderLineBO
     * @param id contains the given id for the OrderLine to be read
     * @param conn contains an already open connection to the DB
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws java.sql.SQLException catches any errors from the SQL execution
     */    
    synchronized OrderLineBO read(String id, Connection conn) throws SQLException, DataException, ConnectionPoolException {        
        ConceptualDAO conceptualDAO = ConceptualDAO.getInstance();
        // check to see if id in the cache
        Cache c = Cache.getInstance();
        OrderLineBO OrderLine = (OrderLineBO)c.get(id);
        if (OrderLine != null){
            return OrderLine;                                                        // if so, return it immediately
        }
        
        // if not in the cache, get a result set from
        // a SELECT * FROM table WHERE id=guid
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM OrderLine WHERE OrderLineID = '" + id + "'");
        conn.commit();
        
        //build the object from the result set
        if (rs.next()) {
            OrderLine = new OrderLineBO(rs.getString("OrderLineID"));
            OrderLine.setPOID(rs.getString("POID"));
            OrderLine.setConceptual((ConceptualBO)conceptualDAO.read(rs.getString("conceptualid")));
            OrderLine.setLineAmount(rs.getDouble("LineAmount"));
            OrderLine.setQuantity(rs.getInt("qty"));
            
            OrderLine.setAlreadyInDB(true);
            OrderLine.setIsDirty(false);            
            
            
            // save to the cache
            c.put(OrderLine.getOrderLineID(), OrderLine);
        }else{
            throw new DataException("Object was not found in the database.");
        }
        stmt.close();
        // return the BO
        return OrderLine;
    }
    
    /**
     * Read all transaction lines for a given transaction
     * 
     * 
     * @return list of OrderLines for the given Transaction
     * @param transID contains the given id for the Transaction to retrieve the lines for
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws java.sql.SQLException catches any errors from the SQL execution
     * @throws edu.byu.isys413.group1E.ConnectionPoolException catches any errors when connecting to the DB.
     */
    public synchronized ArrayList<OrderLineBO> readByPO(String POID) throws DataException, SQLException, ConnectionPoolException{
        ConceptualDAO conceptualDAO = ConceptualDAO.getInstance();
        ArrayList<OrderLineBO> OrderLineList = new ArrayList<OrderLineBO>();
        //now build the query
        String query = "SELECT * FROM OrderLine WHERE POID = ?";

        Connection conn = ConnectionPool.getInstance().get();
        PreparedStatement pstmt = conn.prepareStatement(query);
        pstmt.setString(1, POID);
        ResultSet rs = pstmt.executeQuery();
        conn.commit();
        
        //extract the elements from the result set and build a list of results
        while(rs.next()){
            OrderLineBO OrderLine = new OrderLineBO(rs.getString("OrderLineID"));
            OrderLine.setPOID(POID);
            OrderLine.setConceptual((ConceptualBO)conceptualDAO.read(rs.getString("conceptualid")));
            OrderLine.setLineAmount(rs.getDouble("LineAmount"));    
            OrderLine.setQuantity(rs.getInt("qty"));
            OrderLine.setAlreadyInDB(true);
            OrderLine.setIsDirty(false);
            //add to the list
            OrderLineList.add(OrderLine);
        }
        
        pstmt.close();
        ConnectionPool.getInstance().release(conn);
        return OrderLineList;
    }

    /** Retrieve list of a specific transaction line
     *
     * @param transID contains the given id for the Transaction to be read
     * @param revSrcID contains the given id for the RevenueSource from the OrderLine to be read
     *
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws java.sql.SQLException catches any errors from the SQL execution
     * @throws edu.byu.isys413.group1E.ConnectionPoolException catches any errors when connecting to the DB.
     * @return list of transaction lines for the given transaction containing the given revenueSource
     */
    public synchronized ArrayList<OrderLineBO> retrieveOrderLine(String POID, String conceptualID) throws 
            DataException, SQLException, ConnectionPoolException{
        ConceptualDAO conceptualDAO = ConceptualDAO.getInstance();
        ArrayList<OrderLineBO> OrderLineList = new ArrayList<OrderLineBO>();
        //now build the query
        String query = "SELECT * FROM OrderLine WHERE POID = ? AND ConceptualID = ?";

        Connection conn = ConnectionPool.getInstance().get();
        PreparedStatement pstmt = conn.prepareStatement(query);
        pstmt.setString(1, POID);
        pstmt.setString(2, conceptualID);
        ResultSet rs = pstmt.executeQuery();
        conn.commit();
        
        //extract the elements from the result set and build a list of results
        while(rs.next()){
            OrderLineBO OrderLine = new OrderLineBO(rs.getString("orderlineID"));
            OrderLine.setPOID(POID);
            OrderLine.setConceptual((ConceptualBO)conceptualDAO.read(rs.getString("conceptualid")));
            OrderLine.setLineAmount(rs.getDouble("LineAmount"));    
            OrderLine.setQuantity(rs.getInt("qty"));
            OrderLine.setAlreadyInDB(true);
            OrderLine.setIsDirty(false);
            //add to the list
            OrderLineList.add(OrderLine);
        }
        
        pstmt.close();
        ConnectionPool.getInstance().release(conn);
        return OrderLineList;
    }

        /**
     * Read all transaction lines for a given transaction
     * 
     * 
     * @return list of OrderLines for the given Transaction
     * @param transID contains the given id for the Transaction to retrieve the lines for
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws java.sql.SQLException catches any errors from the SQL execution
     * @throws edu.byu.isys413.group1E.ConnectionPoolException catches any errors when connecting to the DB.
     */
    public synchronized OrderLineBO readByConceptualID(String conceptualID) throws DataException, SQLException, ConnectionPoolException{
        ConceptualDAO conceptualDAO = ConceptualDAO.getInstance();
        OrderLineBO OrderLine = new OrderLineBO();
        //now build the query
        String query = "SELECT * FROM OrderLine WHERE conceptualID = ?";

        Connection conn = ConnectionPool.getInstance().get();
        PreparedStatement pstmt = conn.prepareStatement(query);
        pstmt.setString(1, conceptualID);
        ResultSet rs = pstmt.executeQuery();
        conn.commit();
        
        //extract the elements from the result set and build a list of results
        while(rs.next()){
            OrderLine = new OrderLineBO(rs.getString("orderlineID"));
            OrderLine.setPOID("POID");
            OrderLine.setConceptual((ConceptualBO)conceptualDAO.read(rs.getString("conceptualid")));
            OrderLine.setLineAmount(rs.getDouble("LineAmount"));    
            OrderLine.setQuantity(rs.getInt("qty"));
            OrderLine.setAlreadyInDB(true);
            OrderLine.setIsDirty(false);
        }
        pstmt.close();
        ConnectionPool.getInstance().release(conn);
        return OrderLine;
    }
    
    /**Retrieve list of all transaction Lines
     *
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws java.sql.SQLException catches any errors from the SQL execution
     * @throws edu.byu.isys413.group1E.ConnectionPoolException catches any errors when connecting to the DB.
     * @return list of all transaction lines
     */
    public synchronized ArrayList<OrderLineBO> readAllOrderLine() throws DataException, SQLException, ConnectionPoolException{
        ConceptualDAO conceptualDAO = ConceptualDAO.getInstance();
        ArrayList<OrderLineBO> OrderLineList = new ArrayList<OrderLineBO>();
        //now build the query
        String query = "SELECT * FROM Transaction_Line";

        Connection conn = ConnectionPool.getInstance().get();
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        conn.commit();
        
        //extract the elements from the result set and build a list of results
        while(rs.next()){
            OrderLineBO OrderLine = new OrderLineBO(rs.getString("orderlineID"));
            OrderLine.setPOID("POID");
            OrderLine.setConceptual((ConceptualBO)conceptualDAO.read(rs.getString("conceptualid")));
            OrderLine.setLineAmount(rs.getDouble("LineAmount"));    
            OrderLine.setQuantity(rs.getInt("qty"));
            OrderLine.setAlreadyInDB(true);
            OrderLine.setIsDirty(false);
            //add to the list
            OrderLineList.add(OrderLine);
        }
        
        stmt.close();
        ConnectionPool.getInstance().release(conn);
        return OrderLineList;
    }

    //////////////////////////////////
    ///   UPDATE
    
    /**
     * This is the public save method.  It is what is called when
     * the user (controller) code wants to save or update an object
     * into the database.
     * 
     *@param OrderLineIn contains the OrderLine object to be saved
     *
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws edu.byu.isys413.group1E.ConnectionPoolException catches any errors when connecting to the DB.  
     */
    public synchronized void save(OrderLineBO OrderLineIn) throws DataException, ConnectionPoolException {
        
        try {
            Connection conn = ConnectionPool.getInstance().get();
            try {
                this.save(OrderLineIn, conn);                                   // call save with a connection
                conn.commit();
            } catch (ConnectionPoolException ex) {
                conn.rollback();
                ex.printStackTrace();
            } catch (DataException ex) {
                conn.rollback();
                ex.printStackTrace();
            } catch (SQLException ex) {
                conn.rollback();
                ex.printStackTrace();
                throw new SQLException();
            }
            ConnectionPool.getInstance().release(conn);                       // release the connection
        }catch (SQLException e) {
            throw new DataException("Could not retrieve record for TransactionLineID = " + OrderLineIn.getOrderLineID(), e);
        }catch (ConnectionPoolException x){
            throw new ConnectionPoolException("Could not establish connection to database.", x);
        }
        
        // release the connection back to the pool
        return;
    }
    
    /**
     *  This is a package method that is called by the public save (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     *
     *  By having other DAOs call this save method (rather than update or
     *  insert below, each DAO in a chained save (like the OrderLineDAO calling
     *  MembershipDAO calling InterestDAO save chain) can independently decide
     *  whether to udpate or insert the BO it's saving.
     *
     * @param OrderLine contains the OrderLineBO to save to the DB
     * @param conn contains an already open connection to the DB
     *
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws java.sql.SQLException catches any errors from the SQL execution
     * @throws edu.byu.isys413.group1E.ConnectionPoolException catches any errors when connecting to the DB.
     */
    synchronized void save(OrderLineBO OrderLine, Connection conn) throws SQLException, DataException, ConnectionPoolException {
        // call save(bo, conn) on any subobjects (like OrderLineDAO to MembershipDAO)
        /*Coupon and RevenueSource objects should already exist in the DB and are not modified by
         *a transaction taking place.  Therefore, we will not save them here.
         */
        
        // run update or insert
        if (OrderLine.isIsDirty()) {
            if (OrderLine.isAlreadyInDB()) {
                update(OrderLine, conn);
            }else{
                insert(OrderLine, conn);
            }
            // set the dirty flag to false now that we've saved it
            OrderLine.setIsDirty(false);
        }

                
        // touch the cache for the object
        Cache c = Cache.getInstance();
        c.put(OrderLine.getOrderLineID(), OrderLine);
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL udpate statement and make it more readable.  But
     * logically, it's really just a part of save.
     *
     * @param OrderLine contains the OrderLineBO to save to the DB
     * @param conn contains an already open connection to the DB
     *
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws java.sql.SQLException catches any errors from the SQL execution
     */
    private synchronized void update(OrderLineBO OrderLine, Connection conn) throws SQLException, DataException {
        //update the DB
        PreparedStatement pstmt = conn.prepareStatement("UPDATE OrderLine SET OrderLineID = ?, " +
                "ConceptualID = ?, POID = ?, LineAmount = ?, qty = ? WHERE OrderLineID = ?");
        pstmt.setString(1, OrderLine.getOrderLineID());
        pstmt.setString(2, OrderLine.getConceptual().getProductID());
        pstmt.setString(4, OrderLine.getPOID());
        pstmt.setDouble(5, OrderLine.getLineAmount());
        pstmt.setInt(6, OrderLine.getQuantity());
        pstmt.setString(7, OrderLine.getOrderLineID());
        pstmt.executeUpdate();     
        pstmt.close();
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL insert statement and make it more readable.  But
     * logically, it's really just a part of save.
     *
     * @param OrderLine contains the OrderLineBO to save to the DB
     * @param conn contains an already open connection to the DB
     *
     * @throws edu.byu.isys413.group1E.DataException catches any errors with incoming data
     * @throws java.sql.SQLException catches any errors from the SQL execution
     */
    private synchronized void insert(OrderLineBO OrderLine, Connection conn) throws SQLException, DataException {
       PreparedStatement pstmt = conn.prepareStatement("INSERT INTO OrderLine (OrderLineID, ConceptualID, " +
               " POID, lineamount, qty) VALUES (?, ?, ?, ?, ?)");
        pstmt.setString(1, OrderLine.getOrderLineID());
        pstmt.setString(2, OrderLine.getConceptual().getProductID());
        pstmt.setString(3, OrderLine.getPOID());
        pstmt.setDouble(4, OrderLine.getLineAmount());
        pstmt.setInt(5, OrderLine.getQuantity());
        pstmt.executeUpdate();
        
        // tell the object that it's now in the db (so we call update next time not insert)
        OrderLine.setAlreadyInDB(true);
    }
        
    ///////////////////////////////////////////////////////////////////////////////
    /////////   DELETE
    
    /** I did not include the DELETE functionality intentionally due to instructions received, as well as 
     * to protect the integrity of the data.
     */
    
//    
//    
//    public synchronized OrderLineBO getbyRSID(String RSID) throws 
//            DataException, SQLException, ConnectionPoolException{
//        ArrayList<OrderLineBO> OrderLineList = new ArrayList<OrderLineBO>();
//        //now build the query
//        String query = "SELECT * FROM Transaction_Line WHERE RevenueSourceID = ?";
//
//        Connection conn = ConnectionPool.getInstance().get();
//        PreparedStatement pstmt = conn.prepareStatement(query);
//        pstmt.setString(1, RSID);
//        ResultSet rs = pstmt.executeQuery();
//        conn.commit();
//        
//        OrderLineBO OrderLine = new OrderLineBO();
//        //extract the elements from the result set and build a list of results
//        while(rs.next()){
//            OrderLine = new OrderLineBO(rs.getString("TransactionLineID"));
//            OrderLine.setTransactionID(rs.getString("TransactionID"));
//            OrderLine.setRevSrc(RSDAO_Factory.getInstance().getDAO(rs.getString("TypeRS")).read(rs.getString("RevenueSourceID"), conn));
//            //set the coupon id if needed
//            if(rs.getString("CouponID") != null){
//                OrderLine.setCoupon(CouponDAO.getInstance().read(rs.getString("CouponID"), conn));
//            }else{
//                CouponBO coup = null;
//                OrderLine.setCoupon(coup);
//            }
//            OrderLine.setLineAmount(rs.getDouble("LineAmount"));
//            OrderLine.setDiscountTaken(rs.getDouble("DiscountTaken"));
//            OrderLine.setAlreadyInDB(true);
//            OrderLine.setIsDirty(false);
//
//        }
//        
//        pstmt.close();
//        ConnectionPool.getInstance().release(conn);
//        return OrderLine;
//    }
  
}
